package com.zygh.lz.controller.pc.role;


import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zygh.lz.entity.Account;
import com.zygh.lz.entity.Section;
import com.zygh.lz.entity.Staff;
import com.zygh.lz.entity.app.AppMenu;
import com.zygh.lz.entity.app.RolePermission;
import com.zygh.lz.entity.role.SysMenu;
import com.zygh.lz.entity.role.SysRoleMenu;
import com.zygh.lz.entity.role.SysUserRole;
import com.zygh.lz.service.AccountService;
import com.zygh.lz.service.SectionService;
import com.zygh.lz.service.StaffService;
import com.zygh.lz.service.role.*;
import com.zygh.lz.stapprove.ResultUtil;
import com.zygh.lz.stapprove.SysPcLog;
import com.zygh.lz.vo.ResultBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.security.Principal;
import java.util.Date;
import java.util.List;

/**
 * @author ms151
 */
@Api(tags = "菜单管理")
@RestController
@RequestMapping("/sys/menu")
public class SysMenuController {


    @Resource
    private SysMenuServiceImpl sysMenuService;
    @Resource
    private SysRoleMenuServiceImpl sysRoleMenuService;
    @Resource
    private StaffService staffService;
    @Resource
    private SysUserRoleServiceImpl sysUserRoleService;
    @Resource
    private AppMenuService appMenuService;
    @Resource
    private RolePermissionServiceImpl rolePermissionService;
    @Resource
    private SectionService sectionService;
@Resource
private AccountService accountService;

    @ApiOperation("用户当前用户的菜单和权限信息")
    @GetMapping("/nav")
    public ResultBean nav(Principal principal) {
        //Staff sysUser = staffService.getOne(new QueryWrapper<Staff>().eq("staff_num", principal.getName()));
       // Staff sysUser = staffService.getByUsername(principal.getName());
        Account sysUser = accountService.getByUsername(principal.getName());
        List<SysUserRole> user_id = sysUserRoleService.list(new QueryWrapper<SysUserRole>().eq("user_id", sysUser.getSysStaffId()));
        if (user_id.size() == 0) {
            return ResultUtil.setError(401, "该账号暂未分配角色，请联系管理员！", null);
        }
        // 获取权限信息 // ROLE_admin,ROLE_normal,sys:user:list,....
        String authorityInfo = sysUserRoleService.getUserAuthorityInfo(sysUser.getSysStaffId().longValue());
        String[] authorityInfoArray = StringUtils.tokenizeToStringArray(authorityInfo, ",");

        // 获取导航栏信息
        List<SysMenuDto> navs = sysMenuService.getCurrentUserNav();
        if(navs==null){
            return ResultUtil.setError(401, "该账号角色未分配菜单，请联系管理员！", null);

        }
        return ResultUtil.setOK("成功", MapUtil.builder()
                .put("authoritys", authorityInfoArray)
                .put("nav", navs)
                .map()
        );
    }


    @ApiOperation("获取用户信息接口")
    @GetMapping("/sys/userInfo")
    public ResultBean userInfo(Principal principal) {


        //Staff sysUser = staffService.getByUsername(principal.getName());
        Account sysUser = accountService.getByUsername(principal.getName());
        SysUserRole role = sysUserRoleService.getOne(new QueryWrapper<SysUserRole>()
                .eq("user_id", sysUser.getSysStaffId())
                .last("limit 1"));
        if (role == null) {
            return ResultUtil.setError(401, "该账号暂未分配角色，请联系管理员！", null);
        }
        Section byId = sectionService.getById(sysUser.getSysSectionId());

        return ResultUtil.setOK("成功", MapUtil.builder()
                .put("id", sysUser.getSysStaffId())
                .put("username", sysUser.getStaffName())
                .put("deptId", sysUser.getSysSectionId())
                .put("roleId", role.getRoleId())
                .put("battalion", byId.getSectionName())
                .put("staffNum", sysUser.getStaffNum())
                .map()
        );
    }

    @ApiOperation("根据用户id获取菜单")
    @GetMapping("/info/{id}")
    //@PreAuthorize("hasAuthority('sys:menu:list')")
    public ResultBean info(@PathVariable(name = "id") Long id) {
        return ResultUtil.setOK("查询成功", sysMenuService.getById(id));
    }

    @ApiOperation("获取菜单列表")
    @GetMapping("/list")
    //@PreAuthorize("hasAuthority('sys:menu:list')")
    public ResultBean list() {
        List<SysMenu> menus = sysMenuService.tree();
        return ResultUtil.setOK("查询成功", menus);
    }

    @ApiOperation("PC菜单查询只查启用")
    @PostMapping("/findAppMenuOpen")
    public ResultBean findAppMenuOpen() {
        return ResultUtil.setOK("查询成功", sysMenuService.treeOpen());
    }

    @ApiOperation("新增菜单")
    @PostMapping("/save")
    @SysPcLog(module = "新增菜单信息",operation = "新增")
    //@PreAuthorize("hasAuthority('sys:menu:save')")
    public ResultBean save(@Validated @RequestBody SysMenu sysMenu) {
        sysMenu.setCreated(new Date());

        return sysMenuService.save(sysMenu) ? ResultUtil.setOK("新增成功", null) : ResultUtil.setError(500, "新增失败", null);
    }


    @ApiOperation("修改菜单")
    @PostMapping("/update")
    @SysPcLog(module = "修改菜单信息",operation = "修改")
    //@PreAuthorize("hasAuthority('sys:menu:update')")
    public ResultBean update(@Validated @RequestBody SysMenu sysMenu) {
        sysMenu.setUpdated(new Date());
        return sysMenuService.updateById(sysMenu) ? ResultUtil.setOK("修改成功", null) : ResultUtil.setError(500, "修改失败", null);
    }


    @ApiOperation("删除菜单")
    @PostMapping("/delete/{id}")
    @SysPcLog(module = "删除菜单信息",operation = "删除")
    //@PreAuthorize("hasAuthority('sys:menu:delete')")
    public ResultBean delete(@PathVariable("id") Long id) {

        int count = sysMenuService.count(new QueryWrapper<SysMenu>().eq("parent_id", id));
        if (count > 0) {
            return ResultUtil.setError(500, "请先删除子菜单", null);
        }

        sysMenuService.removeById(id);
        // 同步删除中间关联表
        sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>().eq("menu_id", id));
        return ResultUtil.setOK("删除成功", null);
    }


    @ApiOperation("APP菜单新增")
    @PostMapping("/saveAppMenu")
    public ResultBean saveAppMenu(@Validated @RequestBody AppMenu appMenu) {

        return appMenuService.save(appMenu) ? ResultUtil.setOK("新增成功", null) : ResultUtil.setError(500, "新增失败", null);
    }

    @ApiOperation("APP菜单修改")
    @PostMapping("/updateAppMenu")
    public ResultBean updateAppMenu(@Validated @RequestBody AppMenu appMenu) {
        return appMenuService.updateById(appMenu) ? ResultUtil.setOK("修改成功", null) : ResultUtil.setError(500, "修改失败", null);

    }

    @ApiOperation("APP菜单查询")
    @PostMapping("/findAppMenuAll")
    public ResultBean findAppMenuAll() {
        return ResultUtil.setOK("查询成功", appMenuService.tree());
    }


    @ApiOperation("APP菜单删除")
    @PostMapping("/deleteAppMenu/{id}")
    public ResultBean deleteAppMenu(@PathVariable("id") Long id) {
        int count = appMenuService.count(new QueryWrapper<AppMenu>().eq("app_menu_pid", id));
        if (count > 0) {
            return ResultUtil.setError(500, "请先删除子菜单", null);
        }

        appMenuService.removeById(id);
        // 同步删除中间关联表
        rolePermissionService.remove(new QueryWrapper<RolePermission>().eq("permission_id", id));
        return ResultUtil.setOK("删除成功", null);
    }


}
